<template>
  <view class="profile-container">
    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-info">
        <view class="avatar-section">
          <view class="user-avatar">
            <image
              :src="userInfo.avatar"
              class="avatar-image"
              mode="aspectFit"
            ></image>
          </view>
        </view>

        <view class="user-details">
          <text class="username">{{ userInfo.username }}</text>
          <view class="info-flex">
            <view class="contact-info">
              <text class="phone-text">手机: {{ userInfo.mobile }}</text>
              <view class="edit-icon" @click="goToUnbindPhone"
                ><image src="/static/images/edit.png" mode="aspectFit"></image
              ></view>
            </view>
            <view class="user-id-section">
              <text class="user-id">ID: {{ userInfo.id }}</text>
              <text class="copy-btn" @click="copyUserId">复制</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 会员状态卡片 -->
    <view class="membership-card" v-if="userInfo.totalDays > 0">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ userInfo.packageName }}</text>
          <view class="stat-label">
            <text class="label-text">会员天数</text>
            <text class="question-icon">{{ userInfo.remainingDays }}</text>
          </view>
          <view class="upgrade-btn" @click="goToRecharge">
            <text class="upgrade-btn-text">充值中心</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 会员升级卡片 -->
    <view class="upgrade-card" v-if="userInfo.totalDays == 0">
      <view class="upgrade-info">
        <text class="upgrade-status">普通用户</text>
        <view class="upgrade-btn" @click="goToRecharge">
          <text class="upgrade-btn-text">点击升级会员</text>
        </view>
      </view>
    </view>

    <!-- 升级提示 -->
    <view class="upgrade-section" v-if="userInfo.totalDays == 0">
      <text class="upgrade-text">升级解锁全部功能</text>
    </view>

    <!-- 功能选项列表 -->
    <view class="options-list">
      <!-- 邀请好友 -->
      <view class="option-item" @click="handleInviteFriends">
        <view class="option-left">
          <view class="option-icon"
            ><image src="/static/images/member.png" mode="aspectFit"></image
          ></view>
          <text class="option-text">邀请好友</text>
        </view>
        <view class="copy-link-btn" @click.stop="copyInviteLink">
          <text class="copy-link-text">复制链接</text>
        </view>
      </view>
      <!-- 根据是否为代理商显示不同选项 -->
      <view
        v-if="userInfo.deptType != 'merchant'"
        class="option-item"
        @click="goToAgentJoin"
      >
        <view class="option-left">
          <view class="option-icon"
            ><image src="/static/images/post-share.png" mode="aspectFit"></image
          ></view>
          <text class="option-text">加入代理商</text>
        </view>
        <text class="arrow-icon">></text>
      </view>
      <view v-else class="option-item" @click="goToPromotionCenter">
        <view class="option-left">
          <view class="option-icon"
            ><image src="/static/images/post-share.png" mode="aspectFit"></image
          ></view>
          <text class="option-text">推广中心</text>
        </view>
        <text class="arrow-icon">></text>
      </view>
      <view class="option-item" @click="showInviteCodeDialog">
        <view class="option-left">
          <view class="option-icon"
            ><image src="/static/images/eperson.png" mode="aspectFit"></image
          ></view>
          <text class="option-text">邀请码</text>
        </view>
        <text class="arrow-icon">></text>
      </view>
      <!-- 退出登录 -->
      <view class="option-item" @click="handleLogout">
        <view class="option-left">
          <view class="option-icon"
            ><image src="/static/images/exit.png" mode="aspectFit"></image
          ></view>
          <text class="option-text">退出登录</text>
        </view>
        <text class="arrow-icon">></text>
      </view>
    </view>
  </view>

  <!-- 输入邀请码弹窗 -->
  <view
    class="modal-overlay"
    v-if="showInviteCodeModal"
    @click="hideInviteCodeDialog"
  >
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">邀请码</text>
        <view class="close-btn" @click="hideInviteCodeDialog">×</view>
      </view>
      <view class="modal-body">
        <input
          type="text"
          v-model="inputInviteCode"
          placeholder="请输入邀请码"
          class="invite-code-input"
        />
      </view>
      <view class="modal-footer">
        <button class="cancel-btn" @click="hideInviteCodeDialog">取消</button>
        <button class="confirm-btn" @click="submitInviteCode">确定</button>
      </view>
    </view>
  </view>
</template>

<script>
import { userAPI } from "../../utils/api.js";
import { uploadFile, post } from "../../utils/request.js";
export default {
  data() {
    return {
      userInfo: uni.getStorageSync("userInfo") || {
        id: "",
        username: "",
        phone: "",
        avatar: "/static/icons/robot-avatar.png",
      },
      inviteLink: "",
      inviteCode: "",
      isAgent: false,
      urlParams: {},
      showInviteCodeModal: false,
      inputInviteCode: "",
    };
  },

  onShow() {
    // 检查登录状态
    this.checkLoginStatus();
    // 获取用户信息
    this.getUserInfo();
  },

  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync("token");
      if (!token) {
        uni.reLaunch({
          url: "/pages/login/login",
        });
      }
    },

    // 显示邀请码弹窗
    showInviteCodeDialog() {
      this.inputInviteCode = "";
      this.showInviteCodeModal = true;
    },

    // 隐藏邀请码弹窗
    hideInviteCodeDialog() {
      this.showInviteCodeModal = false;
    },

    // 提交邀请码
    async submitInviteCode() {
      if (!this.inputInviteCode) {
        uni.showToast({
          title: "请输入邀请码",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "提交中...",
        });

        // 调用绑定邀请码接口
        const response = await post("/api/dify/member/bindInviteCode", {
          inviteCode: this.inputInviteCode.trim(),
        });

        uni.hideLoading();
        console.log("response", response.code);
        if (response.code === 0) {
          uni.showToast({
            title: "邀请码绑定成功",
            icon: "success",
          });
          // 重新获取用户信息以更新状态
          this.getUserInfo();
          this.hideInviteCodeDialog();
        } else {
          uni.showToast({
            title: response.message || "邀请码绑定失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("绑定邀请码失败:", error);
        uni.hideLoading();
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      }
    },

    // 获取登录用户信息（admin/member/info）
    //获取会员信息  '/api/dify/member/info',
    async getUserInfo() {
      try {
        const token = uni.getStorageSync("token");
        if (!token) {
          return;
        }

        const res = await userAPI.getUserInfo();
        const memberRes = await userAPI.getMemberInfo();

        const resp = res?.data || {};
        console.log("resp", resp);
        if (resp) {
          this.userInfo = {
            ...this.userInfo,
            ...resp,
          };
          this.inviteCode = resp.inviteCode;
          // 更新邀请链接，包含邀请码
          this.inviteLink = location.origin + `/?ref=${this.inviteCode}`;
        }
        const memberResp = memberRes?.data || {};
        if (memberResp) {
          this.userInfo = {
            ...this.userInfo,
            ...memberResp,
          };
        }
        console.log("memberResp", memberResp);
        uni.setStorageSync("userInfo", this.userInfo);
        console.log(this.userInfo);
      } catch (e) {
        const cached = uni.getStorageSync("userInfo");
        if (cached) {
          this.userInfo = { ...this.userInfo, ...cached };
        }
      }
    },

    // 上传头像
    async uploadAvatar() {
      try {
        // 调用uni的选择图片接口
        const [chooseResult] = await uni.chooseImage({
          count: 1,
          sizeType: ["compressed"],
          sourceType: ["album", "camera"],
        });

        // 显示加载提示
        uni.showLoading({
          title: "上传中...",
        });

        // 调用上传文件接口
        const uploadResult = await uploadFile(chooseResult.tempFilePaths[0]);

        // 上传成功后更新用户头像
        if (uploadResult && uploadResult.data && uploadResult.data.url) {
          this.userInfo.avatar = uploadResult.data.url;

          // 更新本地存储的用户信息
          uni.setStorageSync("userInfo", this.userInfo);

          // 显示上传成功提示
          uni.showToast({
            title: "头像上传成功",
            icon: "success",
          });
        } else {
          throw new Error("上传失败，返回数据格式不正确");
        }
      } catch (error) {
        console.error("上传头像失败:", error);
        uni.showToast({
          title: error.message || "上传失败，请重试",
          icon: "none",
        });
      } finally {
        // 隐藏加载提示
        uni.hideLoading();
      }
    },

    // 复制用户ID
    copyUserId() {
      const idText = this.userInfo?.id ? String(this.userInfo.id) : "";
      if (!idText) {
        uni.showToast({ title: "暂无ID", icon: "none" });
        return;
      }
      uni.setClipboardData({
        data: idText,
        success: () => {
          uni.showToast({
            title: "用户ID已复制",
            icon: "success",
          });
        },
      });
    },

    // 跳转到充值页面
    goToRecharge() {
      uni.navigateTo({
        url: "/pages/recharge/recharge",
      });
    },

    // 处理邀请好友
    handleInviteFriends() {
      // 复制邀请链接
      this.copyInviteLink();
      // 提示用户打开微信分享
      uni.showToast({
        title: "邀请链接已复制，请打开微信分享",
        icon: "none",
        duration: 3000,
      });
    },

    // 跳转到解绑手机号页面
    goToUnbindPhone() {
      uni.navigateTo({
        url: "/pages/unbind-phone/unbind-phone",
      });
    },

    // 复制邀请链接
    copyInviteLink() {
      uni.setClipboardData({
        data: this.inviteLink,
        success: () => {
          uni.showToast({
            title: "邀请链接已复制",
            icon: "success",
          });
        },
      });
    },

    // 处理退出登录
    handleLogout() {
      uni.showModal({
        title: "确认退出",
        content: "确定要退出登录吗？",
        success: (res) => {
          if (res.confirm) {
            // 清除登录状态
            uni.removeStorageSync("token");
            uni.removeStorageSync("openId");
            uni.removeStorageSync("userInfo");

            // 跳转到登录页
            uni.reLaunch({
              url: "/pages/login/login",
            });
          }
        },
      });
    },

    // 跳转到代理加盟页面
    goToAgentJoin() {
      uni.navigateTo({
        url: "/pages/agent-join/agent-join",
      });
    },

    // 跳转到推广中心页面
    goToPromotionCenter() {
      uni.navigateTo({
        url: "/pages/promotion-center/promotion-center",
      });
    },
  },
};
</script>

<style scoped>
.profile-container {
  background-color: #3a3052;
}

/* 用户信息头部 */
.user-header {
  padding: 15px;
  background-color: #3a3052;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar-section {
  margin-right: 16px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  background-color: #e8b070;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  position: relative;
}

.avatar-image {
  width: 60px;
  height: 60px;
}

.avatar-upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.user-avatar:active .avatar-upload-mask {
  opacity: 1;
}

.upload-text {
  color: #ffffff;
  font-size: 16px;
  text-align: center;
}

.user-details {
  flex: 1;
}

.username {
  color: #ffffff;
  font-size: 22px;
  font-weight: bold;
  display: block;
}
.info-flex {
  display: flex;
  align-items: center;
}

.user-id-section {
  display: flex;
  align-items: center;
}

.user-id {
  color: #8f82a8;
  font-size: var(--font-size-small);
  margin-right: 8px;
}

.copy-btn {
  color: #f0d9b5;
  font-size: var(--font-size-small);
  cursor: pointer;
}

/* 会员状态卡片 */
.membership-card {
  background-color: #e8b070;
  border-radius: 16px;
  padding: 20px;
  margin: 0 15px 20px;
  position: relative;
  overflow: hidden;
}
.contact-info {
  display: flex;
  align-items: center;
}

.phone-text {
  color: #8f82a8;
  font-size: var(--font-size-small);
  margin-right: 8px;
}

.edit-icon image {
  width: 16px;
  height: 16px;
  opacity: 0.6;
  margin-right: 20px;
}

.stats-grid {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  color: #333;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
  display: block;
}

.stat-label {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.label-text {
  color: #333;
  font-size: 16px;
  margin-right: 4px;
}

.question-icon {
  color: #666;
  font-size: 26px;
}

.stat-divider {
  width: 1px;
  height: 40px;
  background-color: #d4c4a8;
}

/* 升级提示 */
.upgrade-section {
  text-align: center;
  margin-bottom: 20px;
}

.upgrade-text {
  color: #ffffff;
  font-size: 20px;
  font-weight: 500;
}

/* 会员升级卡片 */
.upgrade-card {
  background-color: #e8b070;
  border-radius: 16px;
  padding: 20px;
  margin: 0 10px 20px;
}

.upgrade-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upgrade-status {
  color: #333;
  font-size: 20px;
  font-weight: 500;
}

.upgrade-btn {
  background-color: #f44336;
  border-radius: 20px;
  padding: 8px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upgrade-btn:active {
  background-color: #d32f2f;
  transform: scale(0.95);
}

.upgrade-btn-text {
  color: #ffffff;
  font-size: 18px;
  font-weight: 500;
}

/* 功能选项列表 */
.options-list {
  padding: 0 20px;
}

.option-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid rgba(143, 130, 168, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.option-item:last-child {
  border-bottom: none;
}

.option-item:active {
  background-color: rgba(74, 64, 98, 0.2);
  border-radius: 8px;
  padding: 16px 8px;
  margin: 0 -8px;
}

.option-left {
  display: flex;
  align-items: center;
}

.option-icon {
  width: 20px;
  margin-right: 12px;
  opacity: 0.6;
}
.option-icon image {
  width: 100%;
  height: 20px;
}

.option-text {
  color: #ffffff;
  font-size: 20px;
}

.arrow-icon {
  color: #8f82a8;
  font-size: 20px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 99;
}

.modal-content {
  width: 80%;
  max-width: 400px;
  background-color: #4a4062;
  border-radius: 12px;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(143, 130, 168, 0.3);
}

.modal-title {
  color: #ffffff;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  color: #8f82a8;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.invite-code-input {
  width: 100%;
  height: 48px;
  background-color: #5a506e;
  border: 1px solid #8f82a8;
  border-radius: 8px;
  padding: 0 16px;
  color: #ffffff;
  font-size: 16px;
  box-sizing: border-box;
}

.invite-code-input::placeholder {
  color: #8f82a8;
}

.modal-footer {
  display: flex;
  border-top: 1px solid rgba(143, 130, 168, 0.3);
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  height: 48px;
  line-height: 48px;
  text-align: center;
  border: none;
  background-color: transparent;
  color: #ffffff;
  font-size: 16px;
  cursor: pointer;
}

.cancel-btn {
  color: #8f82a8;
  border-right: 1px solid rgba(143, 130, 168, 0.3);
}

.confirm-btn {
  color: #f0d9b5;
}

.copy-link-btn {
  background-color: #52496d;
  border-radius: 16px;
  padding: 6px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.copy-link-btn:active {
  background-color: #4a4062;
  transform: scale(0.95);
}

.copy-link-text {
  color: #ffffff;
  font-size: 16px;
}
</style>
